<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item
        ><span style="color: #ccc">商品列表</span></el-breadcrumb-item
      >
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <el-row :gutter="30" style="margin-bottom:20px">
        <!-- 搜索框 -->
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            clearable
            placeholder="请输入内容"
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>

        <!-- 添加用户按钮 -->
        <el-col :span="3">
          <el-button type="primary" @click="addGoods">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 渲染商品数据列表区 -->
      <el-table :data="goodsList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#" width="60"> </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" width="auto">
        </el-table-column>
        <el-table-column prop="goods_price" label="商品价格(￥)" width="110">
        </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量(Kg)" width="110">
        </el-table-column>
        <el-table-column prop="add_time" label="创建时间" width="160">
        </el-table-column>
        <el-table-column label="操作" width="110">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              effect="dark"
              content="修改信息"
              placement="top"
              :enterable="false"
              :open-delay="400"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="showEditDialog(scope.row.goods_id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip
              effect="dark"
              content="删除信息"
              placement="top"
              :enterable="false"
              :open-delay="400"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="removeGoods(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 12, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑商品信息"
      :visible.sync="editDialogVisiable"
      width="50%"
    >
      <!-- 表单区 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="auto"
      >
        <el-form-item label="商品名称 :" prop="goods_name">
          <el-input v-model="editForm.goods_name" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品价格(￥) :" prop="goods_price">
          <el-input v-model="editForm.goods_price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量(Kg) :" prop="goods_weight">
          <el-input v-model="editForm.goods_weight" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品数量 :" prop="goods_number">
          <el-input v-model="editForm.goods_number" type="number"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "GoodsList",
  data() {
    return {
      // 获取商品列表的参数对象
      queryInfo: {
        query: "", //搜索关键字
        pagenum: 1, //当前页码
        pagesize: 5, //当前页显示多少条数据
      },
      goodsList: [],
      total: 0, //用来存储总的商品列表条数
      editDialogVisiable: false, //控制编辑表单的显示与隐藏
      editForm: {},
      // 编辑表单的校验规则
      editFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    // 获取商品列表数据
    async getGoodsList() {
      const { data: res } = await this.$http.get("goods", {
        params: this.queryInfo,
      });
      // console.log(res);
      // 判断状态码是否为200
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表数据失败");
      }
      // 先调用时间戳函数，将时间戳转换格式

      // console.log(res);
      res.data.goods.forEach((item) => {
        item.add_time = this.dateFormat(item.add_time);
      });

      // 获取成功，将数据保存到data中的 goodList 数组中
      this.goodsList = res.data.goods;
      // 保存总的商品数
      this.total = res.data.total;
    },

    // 点击添加商品按钮，跳转到添加组件
    addGoods() {
      this.$router.push("goods/add");
    },

    // 点击编辑按钮，获取该id数据，显示编辑对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("goods/" + id);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品信息失败");
      }
      this.editForm = res.data;
      this.editDialogVisiable = true;
    },

    // 点击编辑对话框中的确认按钮，保存修改内容
    saveEdit() {
      // 先进行表单的预校验
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "goods/" + this.editForm.goods_id,
          this.editForm
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新商品信息失败");
        }
        this.$message.success("更新成功");
        // 关闭编辑对话框
        this.editDialogVisiable = false;
        // 更新数据
        this.getGoodsList();
      });
    },

    // 点击删除按钮，根据id进行删除对应商品信息
    removeGoods(row) {
      // console.log(row);
      this.$confirm(
        `此操作将永久删除 ${row.goods_name}信息, 是否继续?`,
        "删除商品信息",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const { data: res } = await this.$http.delete(
            "goods/" + row.goods_id
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功!");
          // 更新数据
          this.getGoodsList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 监听 pagesize 改变事件 （监听当前每页显示多少条数据）
    handleSizeChange(newSize) {
      // 当每页显示数据发生改变时，得到要修改的数据(newSize)
      this.queryInfo.pagesize = newSize;
      // 当得到要修改的数据时，重新发起数据请求
      this.getGoodsList();
    },

    // 监听 页码值 改变的事件    （当前所在的页数）
    handleCurrentChange(newPage) {
      // 当更改当前所在页数时，得到新的页数数据 (newPage)
      this.queryInfo.pagenum = newPage;
      // 得到新的所在页数时，重新发起数据请求
      this.getGoodsList();
    },

    // 将时间戳变成想要的日期格式
    dateFormat(row) {
      var date = new Date(row); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() + " ";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
  },
};
</script>

<style lang="less" scoped></style>
